package comms;

//TODO: Optimization required; too many calls to the tokenize method for each URI.
public class URIParser {
	private static final int PROTOCOL_INDEX = 0;
	private static final int ADDRESS_INDEX = 1;
	private static final int PARAMS_INDEX = 2;
	private static final char ADDRESS_DELIM = ':';
	private static final char PARAM_DELIM = ';';
	private static final int MAX_TOKENS = 3;

	public static String getURIProtocol(String uri) throws URIException {
		String[] tokens = tokenizeURI(uri);
		return tokens[PROTOCOL_INDEX];
	}
	
	public static String getURIAddress(String uri) throws URIException {
		String[] tokens = tokenizeURI(uri);

		if (tokens[ADDRESS_INDEX].equals("//")) {		
			return "";
		} else {
			System.out.println(tokens[ADDRESS_INDEX].substring(2));
			return tokens[ADDRESS_INDEX].substring(2);
		}
	}
	
	public static String getURIPortAsString(String uri) throws URIException {
		String[] tokens = tokenizeURI(uri);
		return tokens[PARAMS_INDEX];
	}
	
	public static int getURIPortAsInt(String uri) throws URIException {
		String[] tokens = tokenizeURI(uri);
		return Integer.parseInt(tokens[PARAMS_INDEX]);
	}
	
	private static String[] tokenizeURI(String uri) {
		String[] tokens = new String[MAX_TOKENS];
		StringBuffer buff = new StringBuffer(0);
		int i = 0;
		
		for (int j = 0; j < MAX_TOKENS; j++) {
			for ( ; (i < uri.length()) && ((uri.charAt(i) != ADDRESS_DELIM) && (uri.charAt(i) != PARAM_DELIM)); i++) {
				buff.append(uri.charAt(i));
			}
			
			i++;
			tokens[j] = buff.toString();
			buff.setLength(0);
		}
		
		return tokens;
	}
}
